package com.trnnn.strutslit.filter;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.trnnn.strutslit.ActionTable;
import com.trnnn.strutslit.Debug;
import com.trnnn.strutslit.GlobalContext;
import com.trnnn.strutslit.annotation.Action;

public final class ActionCollector {

	
	private ActionCollector() {
	}
	
	public static void init(){
		Debug.output("[ActionCollector] action collector started");
		detectAction();
	}
	private static void detectAction(){
		ClassLoader classLoader=ActionCollector.class.getClassLoader();
		URL url=classLoader.getResource("");
		String classpath=url.getPath().replace("/", File.separator);
		classpath=classpath.substring(1);
		Debug.output("[classpath]: "+classpath);
		File fileRoot=new File(url.getFile());
		List<File> files=new ArrayList<File>();
		getFiles(fileRoot,files);
		for(File file:files){
			String name=file.getPath();
			name=name.replace(classpath, "");
			Debug.output(name);
			String className=name.replace(File.separator, ".");
			className=className.replace(".class", "");
			Debug.output("[classname]: "+className);
			try {
				Class<?> clazz=Class.forName(className);
				GlobalContext.classes.add(clazz);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		parseClass();
	}
	
	private static void parseClass(){
		List<Class<?>> classes=GlobalContext.classes;
		for(Class<?> clazz:classes){
			Method[] methods=clazz.getDeclaredMethods();
			for(Method method: methods){
				if(method.isAnnotationPresent(Action.class)){
					Action action=method.getAnnotation(Action.class);	
					ActionTable.registerActionModel(action,clazz,method);
				}
			}
		}
	}
	
	private static void getFiles(File root,List<File> files){
		File[] subFiles=root.listFiles();
		for(File file : subFiles){
			if(file.isDirectory()){
				getFiles(file,files);
			}
			else{
				files.add(file);
			}
		}
	}
}
